package org.dioib.practice.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dioib.practice.common.constant.StatusCode;

import java.io.Serializable;
import java.util.List;
import java.util.Optional;

public abstract class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> {

    public Result<T> get(T entity) {
        QueryWrapper<T> qw = new QueryWrapper<>();
        qw.setEntity(entity);
        T data = getOne(qw);
        if (data != null)
            return Result.success(data);
        else
            return Result.error(StatusCode.INTERNAL_ERROR);
    }

    public Result<T> read(T entity) {
        return Optional.ofNullable(getOne(new QueryWrapper<T>(entity))).map(Result::success)
                .orElse(Result.error(StatusCode.INTERNAL_ERROR));
    }

    public Result<List<T>> reads(T entity) {
        return Optional.ofNullable(list()).map(Result::success)
                .orElse(Result.error(StatusCode.INTERNAL_ERROR));
    }

    public Result<T> delete(T entity) {
        return removeById(entity) ? Result.success(entity) : Result.error(StatusCode.INTERNAL_ERROR);
    }

    public Result<T> update(T entity) {
        return getBaseMapper().updateById(entity) > 0 ? Result.success(entity) : Result.error(StatusCode.INTERNAL_ERROR);
    }

    public Result<T> create(T entity) {
        return saveOrUpdate(entity) ? Result.success(entity) : Result.error(StatusCode.INTERNAL_ERROR);
    }

    // 以id为条件
    public Result<T> read(Serializable id) {
        return Optional.ofNullable(getBaseMapper().selectById(id)).map(Result::success)
                .orElse(Result.error(StatusCode.INTERNAL_ERROR));
    }

    public Result<T> delete(Serializable id) {
        return removeById(id) ? Result.success() : Result.error(StatusCode.INTERNAL_ERROR);
    }

    public Result<T> delete(List<Serializable> ids) {
        return removeByIds(ids) ? Result.success() : Result.error(StatusCode.INTERNAL_ERROR);
    }

}
